package com.edu.converter;
/*
 * @Author:princess
 * @Date 2023/11/22 11 22 18:58
 *
 */

import org.springframework.core.convert.converter.Converter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

public class MyStringToDateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String source) {
        SimpleDateFormat dft = null;
        Date date = null;
        //正则表达式 判断 前端传递的 字符串满足哪种格式，再创建 相应的SimpleDateFormat 进行转换
        try {
            if (Pattern.matches("^\\d{4}/\\d{1,2}/\\d{1,2}$", source)) {
                dft = new SimpleDateFormat("yyyy/MM/dd");
                date = dft.parse(source);
            }else if(Pattern.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$", source)){
                dft = new SimpleDateFormat("yyyy-MM-dd");
                date = dft.parse(source);
            }else{
                throw new ClassCastException("输入的字符串"+source+"无法转为date类型");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return date;
    }
}
